#include "tcp.h"

#define SERVER_IP_CONFIG_FILE ".serverIpInfo"

int main(int argc, char * argv[]){


	int sockfd, newsockfd, fd;
	FILE * fp = fopen(SERVER_IP_CONFIG_FILE, "r");
	char *ip;
	char *port;
	char buff[BUFSIZ] = {};
	int ret;

	//读取本地文件配置
	readConfig(buff, fp, &ip, &port);
	printf("%s\n%s\n", ip, port);

	//套接字初始化
	sockfd = socketInit(ip, port, true);

	//接收客户端发起的请求，建立套接字
	newsockfd = accept(sockfd, NULL, NULL);
	if(newsockfd < 0){
		ErrorExit("accept");
	}

	//接收客户端上送的文件名,并创建新文件
	bzero(buff, BUFSIZ);
	ret = socketTransport(newsockfd, buff, BUFSIZ, read);
	printf("filename : %s\n", buff);
	fd = open(buff, O_WRONLY|O_CREAT, 0666);
	if(fd < 0){
		ErrorExit("open new file");
	}

	//往客户端发送确认信号
	buff[0] = '1';
	socketTransport(newsockfd, buff, 1, (func_socket_data)write);

	//接收文件内容
	while(1){
		//网络传输来的数据
		ret = socketTransport(newsockfd, buff, BUFSIZ, read);
		if(!ret){
			break;
		}
		//将数据写到新文件中
		socketTransport(fd, buff, ret, (func_socket_data)write);
	}

	close(sockfd);
	close(newsockfd);
	close(fd);
	fclose(fp);
	return 0;
}
